package com.anycl.design.structural.proxy.dynamicproxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Slf4j
public class Main {

    public static void main(String[] args) {
        String name = "anycl";
        IBuyer buyer = new Buyer(name);
        // JDK代理类，第二个参数是目标对象实现的接口类型，所以需要被代理的目标对象实现一个或多个接口
        IBuyer proxy = (IBuyer) Proxy.newProxyInstance(buyer.getClass().getClassLoader(),
                buyer.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object object;
                        // buyTicket操作前后进行通知操作，来模拟BuyerProxy
                        if ("buyTicket".equals(method.getName())) {
                            before();
                            object = method.invoke(buyer, args);
                            after();
                        } else {
                            object = method.invoke(buyer, args);
                        }
                        return object;
                    }
                });
        proxy.login(name, "123456");
        proxy.buyTicket();

    }

    private static void before() {
        log.info("准备定时任务，开始刷票");
    }

    private static void after() {
        log.info("刷票成功，短信通知客户");
    }
}